// 后端接口配置文件
// 请根据您的实际后端接口修改以下配置

// 开发环境配置
const DEV_CONFIG = {
  baseUrl: "http://10.161.3.144:10010/admin-api",  // 后端API地址，使用admin-api接口
  // 接口路径映射 - 映射到雄安系统后端接口
  apiMap: {
    // 用户名+密码登录 (对应Boss端的username+password登录)
    '/addons/ddrive/user/login': '/system/auth/login',
    // 手机号+验证码登录
    '/addons/ddrive/user/mobilelogin': '/system/auth/sms-login',
    // 发送短信验证码
    '/addons/ddrive/user/getcode': '/system/auth/send-sms-code',
    // 微信登录
    '/addons/ddrive/wx_login/wxlogin': '/system/auth/social-login',
    // 获取微信openid  
    '/addons/ddrive/wx_login/getOpenid': '/system/auth/social-auth-redirect',
    // 绑定手机号
    '/addons/ddrive/user/bindOnAccount': '/system/user/bind-mobile',
    // 获取用户详细信息（使用用户profile接口）
    '/addons/ddrive/user/userInfo': '/system/user/profile/get',
    
    // 订单相关接口映射 (使用admin-api路径)
    '/addons/ddrive/order/order_taking': '/ride/app/order/my-orders',  // 获取我的订单列表
    '/addons/ddrive/order/index': '/ride/app/order/my-orders',  // 获取订单列表（通用）
    '/addons/ddrive/order/create': '/ride/app/order/create',  // 创建订单
    '/addons/ddrive/order/detail': '/ride/app/order/detail',  // 订单详情
    '/addons/ddrive/order/cancel': '/ride/app/order/cancel',  // 取消订单
    '/addons/ddrive/order/status': '/ride/app/order/status',  // 订单状态
    '/addons/ddrive/order/estimate': '/ride/app/order/estimate-price',  // 订单预估
    
    // 货运订单相关
    '/addons/ddrive/hyorder/index': '/ride/app/order/my-orders',  // 货运订单列表
    '/addons/ddrive/hyorder/create': '/ride/app/order/create',  // 创建货运订单
    
    // 顺风车订单相关
    '/addons/ddrive/sforder/user_order': '/ride/app/order/my-orders',  // 顺风车用户订单
    '/addons/ddrive/sforder/order_index': '/ride/app/order/my-orders',  // 顺风车订单列表
    '/addons/ddrive/sforder/create': '/ride/app/order/create'  // 创建顺风车订单
  }
};

// 生产环境配置
const PROD_CONFIG = {
  baseUrl: "https://your-production-api.com",  // 您的生产环境后端地址
  apiMap: DEV_CONFIG.apiMap  // 使用相同的接口映射
};

// 根据环境选择配置
let isDev;
// #ifdef H5
isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
// #endif
// #ifndef H5
isDev = true;  // 在APP/小程序环境中默认为开发模式
// #endif

export const BACKEND_CONFIG = isDev ? DEV_CONFIG : PROD_CONFIG;

// 获取真实的API地址
export function getRealApiUrl(originalUrl) {
  const mappedUrl = BACKEND_CONFIG.apiMap[originalUrl];
  return mappedUrl || originalUrl;
}

// 参数转换器 - 将前端参数转换为后端期望的格式
export function transformParams(apiUrl, params) {
  // 根据不同的接口转换参数格式
  switch (apiUrl) {
    case '/system/auth/login':
      // 用户名+密码登录参数转换 (匹配Boss端接口格式)
      return {
        username: params.mobile || params.username,  // 前端用手机号作为用户名
        password: params.password,
        captchaVerification: params.captchaVerification || ''  // 验证码验证(如果需要)
      };
      
    case '/system/auth/sms-login':
      // 手机号+验证码登录参数转换
      return {
        mobile: params.mobile,
        code: params.captcha || params.code
      };
      
    case '/system/auth/send-sms-code':
      // 发送短信验证码参数转换
      return {
        mobile: params.mobile,
        scene: 21  // 21表示登录场景，参考Boss端配置
      };
      
    case '/system/auth/social-login':
      // 微信登录参数转换
      return {
        type: params.type || 'wechat',
        code: params.code,
        state: params.state || ''
      };
      
    case '/system/user/bind-mobile':
      // 绑定手机号参数转换
      return {
        mobile: params.mobile,
        code: params.captcha || params.code
      };
      
    case '/ride/app/order/my-orders':
      // 订单列表参数转换
      return {
        pageNo: params.page || 1,
        pageSize: params.pageSize || 10,
        status: params.status,
        orderType: params.order_type || params.type
      };
      
    case '/ride/app/order/create':
      // 创建订单参数转换
      return {
        city: params.city,
        vehicleClass: params.vehicle_class || params.vehicleClass,
        pickupLocation: params.pickup_location || params.pickupLocation,
        dropoffLocation: params.dropoff_location || params.dropoffLocation,
        paymentMethod: params.payment_method || params.payId || 1
      };
      
    case '/ride/app/order/estimate-price':
      // 订单预估参数转换
      return {
        pickupLat: params.pickupLat || params.pickup_lat,
        pickupLng: params.pickupLng || params.pickup_lng,
        destinationLat: params.destinationLat || params.destination_lat,
        destinationLng: params.destinationLng || params.destination_lng,
        vehicleType: params.vehicleType || params.vehicle_type
      };
      
    default:
      return params;
  }
}

// 响应数据转换器 - 将后端响应转换为前端期望的格式
export function transformResponse(response, apiUrl) {
  if (DEBUG_CONFIG.enableDetailLog) {
    console.log('响应转换 - 接口:', apiUrl, '原始响应:', response);
  }
  
  // 检查是否是前端标准格式 (code: 1 表示成功)
  if (response.code !== undefined && response.data !== undefined && response.msg !== undefined && response.code === 1) {
    return response;
  }
  
  // 雄安系统后端格式处理
  // 格式1: { code: 0, data: {...}, message: "成功" } - 0表示成功
  // 格式2: { code: 200, data: {...}, message: "成功" } - 200表示成功
  if (response.code !== undefined) {
    const transformedData = {
      code: (response.code === 0 || response.code === 200) ? 1 : (response.code === 401 ? 401 : 0),
      data: response.data,
      msg: response.message || response.msg || '操作完成'
    };
    
    // 登录接口特殊处理 - 将token放到正确位置
    if (apiUrl.includes('/system/auth/') && response.data) {
      // 处理登录响应格式，确保token和用户信息格式正确
      if (response.data.accessToken || response.data.token) {
        transformedData.data = {
          accessToken: response.data.accessToken || response.data.token,
          refreshToken: response.data.refreshToken,
          userId: response.data.userId,
          expiresTime: response.data.expiresTime,
          user: response.data.user || response.data.userInfo || {},
          userinfo: response.data.user || response.data.userInfo || {} // 兼容前端代码中的userinfo字段
        };
      }
      
      if (DEBUG_CONFIG.enableDetailLog) {
        console.log('登录响应转换 - 原始code:', response.code, '转换后code:', transformedData.code);
        console.log('登录响应转换:', transformedData);
      }
    }
    
    // 订单列表接口特殊处理
    if (apiUrl.includes('/ride/app/order/my-orders') && response.data) {
      // 处理订单列表响应，转换为前端期望的格式
      const orderData = response.data;
      
      if (orderData.list || Array.isArray(orderData)) {
        // 分页数据格式
        const orders = orderData.list || orderData;
        transformedData.data = orders.map(order => ({
          id: order.orderId,
          order_id: order.orderId,
          order_no: order.orderNo,
          city: order.city,
          vehicle_class: order.vehicleClass,
          order_status: order.orderStatus,
          pickup_location: order.pickupLocation,
          dropoff_location: order.dropoffLocation,
          order_amount: order.orderAmount,
          service_duration: order.serviceDuration,
          service_distance: order.serviceDistance,
          created_at: order.createdAt,
          updated_at: order.updatedAt,
          from_id: order.fromId,
          pay_id: order.payId
        }));
        
        // 如果有分页信息，也要转换
        if (orderData.total !== undefined) {
          transformedData.total = orderData.total;
          transformedData.page = orderData.pageNo || 1;
          transformedData.pageSize = orderData.pageSize || 10;
        }
      } else {
        // 单个订单数据
        transformedData.data = {
          id: orderData.orderId,
          order_id: orderData.orderId,
          order_no: orderData.orderNo,
          city: orderData.city,
          vehicle_class: orderData.vehicleClass,
          order_status: orderData.orderStatus,
          pickup_location: orderData.pickupLocation,
          dropoff_location: orderData.dropoffLocation,
          order_amount: orderData.orderAmount,
          service_duration: orderData.serviceDuration,
          service_distance: orderData.serviceDistance,
          created_at: orderData.createdAt,
          updated_at: orderData.updatedAt,
          from_id: orderData.fromId,
          pay_id: orderData.payId
        };
      }
      
      // 为了兼容货运订单，添加hy字段
      if (apiUrl.includes('hyorder')) {
        transformedData.hy = transformedData.data;
      }
    }
    
    // 用户profile接口特殊处理
    if (apiUrl.includes('/system/user/profile/get') && response.data) {
      // 处理用户profile响应，转换为前端期望的格式
      const userData = response.data;
      
      transformedData.data = {
        // 基本用户信息
        id: userData.id,
        userId: userData.id,
        mobile: userData.mobile,
        nickname: userData.nickname,
        truename: userData.nickname,
        username: userData.username,
        avatar: userData.avatar,
        email: userData.email,
        sex: userData.sex,
        status: 1, // 默认状态为正常
        idcard: '', // profile接口没有身份证信息
        balance: 0, // profile接口没有余额信息
        
        // 实名认证相关
        real_verified: userInfo.realNameStatus || 0,
        realNameStatus: userInfo.realNameStatus || 0,
        realNameTime: userInfo.realNameTime,
        
        // 乘客等级和成长值（从passengerInfo和memberInfo映射）
        level: passengerInfo.level || memberInfo.level || 1,
        growthValue: passengerInfo.growthValue || memberInfo.growthValue || 0,
        
        // 里程统计（从passengerInfo和orderStats映射）
        kilometersAll: passengerInfo.kilometersAll || orderStats.totalDistance || 0,
        kilometersMonth: passengerInfo.kilometersMonth || orderStats.monthDistance || 0,
        
        // 金额统计（从passengerInfo和orderStats映射）
        totalMoney: passengerInfo.totalMoney || 0,
        payMoneyAll: passengerInfo.payMoneyAll || orderStats.totalAmount || 0,
        payMoneyMonty: passengerInfo.payMoneyMonty || orderStats.monthAmount || 0,
        refundMoney: passengerInfo.refundMoney || 0,
        
        // 发票统计（从passengerInfo映射）
        yesInvoice: passengerInfo.yesInvoice || 0,
        noInvoice: passengerInfo.noInvoice || 0,
        
        // 订单统计（从orderStats映射）
        totalOrders: passengerInfo.totalOrders || orderStats.totalCount || 0,
        completedOrders: orderStats.completedCount || 0,
        cancelledOrders: orderStats.cancelledCount || 0,
        monthOrders: orderStats.monthCount || 0,
        avgRating: orderStats.avgRating || 0,
        
        // 会员信息（从memberInfo映射）
        points: memberInfo.points || 0,
        coupon_count: memberInfo.couponCount || 0,
        levelName: memberInfo.levelName || '',
        nextLevelGrowth: memberInfo.nextLevelGrowth || 0,
        
        // 地址信息（预留）
        homeAddress: '',
        workAddress: '',
        emergency_contact: '',
        contact_tel: '',
        
        // 登录时间（从userInfo映射）
        loginDate: userInfo.loginDate,
        createTime: userInfo.createTime
      };
    }
    
    return transformedData;
  }
  
  // 格式2: { success: true, data: {...}, msg: "成功" }  
  if (response.success !== undefined) {
    return {
      code: response.success ? 1 : 0,
      data: response.data,
      msg: response.msg || response.message || '操作完成'
    };
  }
  
  // 格式3: 登录接口特殊处理 - 直接包含token的对象 (适配其他可能的返回格式)
  if (apiUrl.includes('login') && (response.accessToken || response.token)) {
    return {
      code: 1,
      data: {
        accessToken: response.accessToken || response.token,
        refreshToken: response.refreshToken,
        user: response.user || response.userInfo || {},
        userinfo: response.user || response.userInfo || {} // 兼容前端代码
      },
      msg: '登录成功'
    };
  }
  
  // 默认格式化
  return {
    code: 1,
    data: response,
    msg: '操作成功'
  };
}

// 调试模式配置
export const DEBUG_CONFIG = {
  // 是否打印详细日志
  enableDetailLog: true,
  // 是否模拟接口响应（用于后端未准备好时的调试）
  enableMockResponse: false,
  // 模拟响应延迟（毫秒）
  mockDelay: 1000
};

// 模拟响应数据（仅在调试时使用）
export const MOCK_RESPONSES = {
  '/api/user/login': {
    code: 1,
    data: {
      token: 'mock_token_123456',
      userInfo: {
        id: 1,
        mobile: '138****1234',
        nickname: '用户昵称',
        avatar: ''
      }
    },
    msg: '登录成功'
  },
  
  '/api/user/smsLogin': {
    code: 1,
    data: {
      token: 'mock_token_123456',
      userInfo: {
        id: 1,
        mobile: '138****1234',
        nickname: '用户昵称',
        avatar: ''
      }
    },
    msg: '登录成功'
  },
  
  '/api/user/wechatLogin': {
    code: 1,
    data: {
      token: 'mock_token_123456',
      userInfo: {
        id: 1,
        mobile: '',
        nickname: '微信用户',
        avatar: 'https://example.com/avatar.jpg',
        needBindMobile: true
      }
    },
    msg: '登录成功'
  },
  
  '/api/sms/send': {
    code: 1,
    data: {
      messageId: 'msg_123456'
    },
    msg: '验证码发送成功'
  }
};
